import $ from './library/jquery.js';
import cookie from './library/cookie.js';

let shop = JSON.parse((cookie.get('shop')));
let idList = shop.map(ele => ele.id).join(',');

$.ajax({
    type: 'get',
    url: '../../interface/getshop.php',
    data: { idList },
    dataType: 'json'
}).then(res => {

    let string = '';
    let index = 0;
    res.forEach((ele, i) => {
        index = shop.findIndex(el => el.id == ele.id);
        string += `
      <div class=" item-body clear item-normal first-item last-item ">
      <ul class="item-content clear" style="height:129px;">
          <li class="td td-chk">
              <div class="td-inner ">
                  <div style="height: 82px;position: relative; ">
                      <div class="cart-checkbox ">
                          <input type="checkbox" name=" " id=" ">
                      </div>
                  </div>
              </div>
          </li>
          <li class="td td-item">
              <div class="td-inner">
                  <div class="item-pic img-loaded">
                      <a href="javascript:;">
                          <img src="${JSON.parse(res[i].picture)[0].src}
                              " alt=" " class="itempic">
                      </a>
                  </div>
                  <div class="item-info ">
                      <div class="item-basic-info">
                          <a href="javascript:;" class="item-title">
                              ${res[i].tiltle}
                          </a>
                      </div>
                      <div class="item-other-info">
                          <div class="promo-logos"></div>
                          <div class="item-icon-list clear ">
                              <div class="item-icons item-icons-fixed ">
                                  <span class="item-icon item-icon-0 " title="支持信用卡支付 ">
                                      <img src="https://assets.alicdn.com/sys/common/icon/trade/xcard.png " alt=" ">
                                  </span>
                                  <a href="javascript:; " class="item-icon item-icon-1 " title="消费者保障服务，卖家承诺7天退换 ">
                                      <img src="https://img.alicdn.com/tps/i3/T1Vyl6FCBlXXaSQP_X-16-16.png " alt=" ">
                                  </a>
                                  <a href="javascript:; " class="item-icon item-icon-2 " title="消费者保障服务，卖家承诺如实描述 ">
                                      <img src="https://img.alicdn.com/tps/i4/T1BCidFrNlXXaSQP_X-16-16.png " alt=" ">
                                  </a>
                              </div>
                          </div>
                          <div class="item-tips "></div>
                      </div>
                  </div>

              </div>
          </li>
          <li class="td td-info">
              <div class="item-props item-props-can">
                  
              </div>
          </li>
          <li class="td td-price">
              <div class="td-inner">
                  <div class="item-price price-promo-">
                      <div class="price-content">
                          <div class="price-line">
                              <em class="price-original">￥${parseInt(res[i].price) + 10}</em>
                          </div>
                          <div class="price-line">
                              <em class="price-now">￥${res[i].price}</em>
                          </div>
                      </div>
                  </div>
              </div>
          </li>
          <li class="td td-amount">
              <div class="td-inner">
                  <div class="amount-wrapper ">
                      <div class="item-amount ">
                          <a href="javascript:;" class=" no-minus">-</a>
                          <input type="text" value="${shop[index].num}" class="text text-amount" data-max="99999999" data-now="1" autocomplete="off" >
                          <a href="javascript:;" class="plus">+</a>
                      </div>
                      <div class="amount-msg"></div>
                  </div>
              </div>
          </li>
          <li class="td td-sum">
              <div class="td-inner">
                  <em>￥${(shop[index].num * res[i].price).toFixed(2)}</em>
              </div>
          </li>
          <li class="td td-op">
              <div class="td-inner">
                  <a title="移入收藏夹" class="btn-fav J_Fav J_MakePoint" href="javascript:;">移入收藏夹</a>
                  <a href="javascript:;" data-point-url="//www.atpanel.com/jsclick?cache=16340431021252&amp;cartlist=delete" class="J_Del J_MakePoint" data-id="${res[i].id}">删除</a>
                  <div class="find-similar J_find_similar close">
                      <div class="J_find_similar_trigger">
                          <a href="javascript:;" class="new-find-similar">相似宝贝</a>
                          <span class="arrow"></span>
                          <i class="icon-bd-title"></i>
                      </div>
                      <div class="find-similar-body">
                          <img src="" class="find-similar-loading">
                      </div>
                  </div>
              </div>
          </li>
      </ul>

  </div>
      
      `
    });
    $('.item-holder').html(string).find('.J_Del ').on('click', function() {
        let res = shop.filter(el => el.id !== $(this).attr('data-id'));
        cookie.set('shop', JSON.stringify(res), 1);
        location.reload();
    });
    number();
    money();
}).catch(xhr => {
    console.log(xhr.status);
});

function number(num) {
    let input = $('.text-amount');
    let changed = $('.item-amount a');
    // 输入框输入数量
    input.on('input', function() {
        if (this.value == '') {} else if (!Number(this.value)) {
            this.value = '1'
        } else if (parseInt(this.value) >= num) {
            this.value = num
        }
    });
    input.on('change', function() {
            if (this.value == '') {
                this.value = 1;
            }
            add();
        })
        // 加号减号增减数量
    changed.on('click', function() {
        let index = changed.index(this);
        if (index % 2 != 0) {
            $(this).siblings('input')[0].value = parseInt($(this).siblings('input')[0].value) + 1;
        } else {
            if (parseInt($(this).siblings('input')[0].value) > 1) {
                $(this).siblings('input')[0].value -= 1;
            }
        }
        add();
    });

    // 计算每个商品价格
    function add() {
        $('.text-amount').each((i, ele) => {
            let yuan = parseFloat($(ele).val() * $(ele).parents('.item-body').find('.price-now').text().slice(1)).toFixed(2);
            $(ele).parents('.item-body').find('.td-inner em:eq(2)').text("￥" + yuan);
        })
    }
}

function money() {
    // 选择框
    $(".cart-checkbox input:first").on("click", function() {
        $(".cart-checkbox input:not(:first)").prop(
            "checked",
            $(".cart-checkbox input:first").prop("checked")
        );
        jisuan();
    });

    function isTrue() {
        let arr = $(".cart-checkbox input:not(:first)").toArray();
        return arr.every((ele) => $(ele).prop("checked"));
    }
    $(".cart-checkbox input:not(:first)").on("click", function() {
        $(".cart-checkbox input:first").prop("checked", isTrue());
        jisuan();
    });
    // 计算总价格
    function jisuan() {
        let yuan = 0;
        // 获取所有被选中的商品，价格总和
        $(".cart-checkbox input:not(:first)").each((i, ele) => {
                if ($(ele).prop("checked")) {
                    yuan += parseInt($(ele).parents('.item-body').find('.td-inner em:eq(2)').text().slice(1));
                }
            })
            // 把计算得到的价格放入结算框
        $('.price em').html("&nbsp;" + yuan.toFixed(2));
        // 结算框颜色变化
        if (yuan !== 0) {
            $('.submit-btn').css('background-color', "#FF4400")
        } else {
            $('.submit-btn').css('background-color', "#AAAAAA")
        }
    }
}